package com.dc.juc.example._11_lock;

import com.dc.juc.annoations.ThreadSafe;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Description: ReentrantLock   可重入锁
 *
 *  保证了 普通变量 ‘++’操作的线程安全
 *
 * @author: gdc
 * @date: 2021/8/16
 * @version 1.0
 */
@ThreadSafe
@Slf4j
public class _1_ReentrantLock {

    /**
     * 请求总数
     */
    public static int CLIENT_TOTAL = 5000;
    /**
     * 同时并发执行的线程数
     */
    public static int THREAD_TOTAL = 200;
    /**
     * 累计变量
     */
    public static int COUNT = 0;

    /**
     * ReentrantLock    可重入锁
     */
    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(THREAD_TOTAL);
        CountDownLatch countDownLatch = new CountDownLatch(CLIENT_TOTAL);

        for (int i = 0; i < CLIENT_TOTAL; i++) {
            threadPool.execute(() -> {
                try {
                    semaphore.acquire();

                    add();

                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("异常信息为：{}", Throwables.getStackTraceAsString(e));
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        countDownLatch.await();

        threadPool.shutdown();
        log.info("count:{}", COUNT);
    }

    /**
     * COUNT 计数 +1， 通过 ReentrantLock 完成加锁操作
     */
    private static void add() {
        // lock() 解锁
        lock.lock();
        try {
            COUNT++;
        } finally {

            // unlock() 解锁，且必须存放到 finally块中
            lock.unlock();
        }
    }
}
